package com.tool.creatBean;

import com.core.jdbc.SqlHelper;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CreateHelperNew {
    public static void main(String[] args) {
        getTableInfo("message_need,message_finish,message_msg", "待办消息,已办消息,普通消息", "E:/kkkll/");
    }

    /**
     * @param table    表名
     * @param describe 表模块描述
     * @param path     生成bean文件路径
     */
    public static void getTableInfo(String table, String describe, String path) {
        try {
            Connection con = SqlHelper.getConnect();
            DatabaseMetaData dbmd = con.getMetaData();
            String[] describeList = describe.split(",");
            String[] tablenames = table.split(",");
            //获取所有表名
            //   ResultSet tableRet = dbmd.getTables(null, null, null, null);
//          while (tableRet.next()) {
//                String tableName = (String) tableRet.getObject("TABLE_NAME");
//                System.out.println(tableName);
//          }
            int i = 0;
            for (String tablename : tablenames) {

                //获取多个字段和类型
                ResultSet set = dbmd.getColumns(null, "%", tablename, "%");

                TableInfo tableInf = new TableInfo();
                tableInf.setTablename(tablename);
                tableInf.setDescribe(describeList[i]);
                i++;
                String id = "";
                //获取多个主键
                ResultSet set2 = dbmd.getPrimaryKeys(null, "%", tablename);
                while (set2.next()) {
                    String key = set2.getString("COLUMN_NAME");
                    id = key;
                    tableInf.setId(id);
                }
                while (set.next()) {
                    String key = set.getString("COLUMN_NAME");
                    String type = set.getString("TYPE_NAME");
                    String remark = set.getString("REMARKS");

                    Column c = new Column();
                    c.setName(key);
                    c.setBigname(upperFirstLatter(key));
                    c.setDescribe(remark);
                    type = type.split(" ")[0];
                    c.setType(toType(type));
                    tableInf.putKeys(key, type);
                    if (key.equals(id)) {
                        tableInf.setIdColumn(c);
                    } else {
                        tableInf.addCol(c);
                    }

                }

                createPoFile(tableInf, path);

            }


        } catch (SQLException | IOException e) {
            e.printStackTrace();

        }
    }

    public static void createPoFile(TableInfo tableInfo, String path) throws IOException {
        if (path == null) path = "E:/kkk/";

        //初始化代码
        String root = CreateHelperNew.class.getClassLoader().getResource("").getPath() + "codeTemplate";
        System.out.println(root);
        FileResourceLoader resourceLoader = new FileResourceLoader(root, "utf-8");
        Configuration cfg = Configuration.defaultConfiguration();
        GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
        Template t = gt.getTemplate("/bean");
        bindTemplate(tableInfo, t);
        //渲染结果
        String resultBean = t.render();

        Template t2 = gt.getTemplate("/action");
        bindTemplate(tableInfo, t2);
        String resultAction = t2.render();

        BufferedWriter bw = null;
        try {
            //生成文件夹
            File fRoot = new File(path);
            if (!fRoot.exists()) fRoot.mkdir();
            if (!fRoot.isDirectory()) throw new RuntimeException("请传入目录路径");
            File ftable = new File(path + "/" + tableInfo.getTablename() + "/");
            if (!ftable.exists()) ftable.mkdir();
            File fAction = new File(path + tableInfo.getTablename() + "/action/");
            if (!fAction.exists()) fAction.mkdir();
            File fBean = new File(path + tableInfo.getTablename() + "/domain/");
            if (!fBean.exists()) fBean.mkdir();

            File fBean2 = new File(path + "/domain/");
            if (!fBean2.exists()) fBean2.mkdir();

            //生成实体bean文件
            String filename = upperFirstLatter(tableInfo.getTablename()) + ".java";
            //File f = new File(path +tableInfo.getTablename()+ "/domain/" + filename);
            File f = new File(path + "/domain/" + filename);

            //将源码写入文件
            bw = new BufferedWriter(new FileWriter(f.getAbsoluteFile()));
            bw.write(resultBean);
            bw.close();

            //生成action文件
            String filename2 = tableInfo.getTablename() + "Action.java";
            File f2 = new File(path + tableInfo.getTablename() + "/action/" + filename2);
            //将源码写入文件
            bw = new BufferedWriter(new FileWriter(f2.getAbsoluteFile()));
            bw.write(resultAction);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                    bw = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    private static void bindTemplate(TableInfo tableInfo, Template t) {
        t.binding("tablename", tableInfo.getTablename());
        t.binding("Tablename", upperFirstLatter(tableInfo.getTablename()));
        t.binding("describe", tableInfo.getDescribe());
        //主键字段
        t.binding("id", tableInfo.getIdColumn());
        //普通字段
        t.binding("list", tableInfo.getColList());
    }


    public static String toType(String column) {
        switch (column.toLowerCase()) {
            case "varchar":
            case "char":
                return "String";
            case "smallint":
            case "int":
            case "tinyint":
                return "Integer";
            case "bigint":
                return "Long";
            case "double":
                return "Double";
            case "float":
                return "Double";
            case "clob":
                return "java.sql.Clob";
            case "blob":
                return "java.sql.Blob";
            case "date":
                return "String";
            case "datetime":
                return "String";
            case "timestamp":
                return "String";
            case "text":
                return "String";
            default:
                return null;
        }

    }


    /**
     * 转大写
     *
     * @param name
     * @return
     */
    public static String upperFirstLatter(String name) {
        return name.substring(0, 1).toUpperCase() + name.substring(1);
    }

}